# -*- coding: utf-8 -*-
# @name             : 文件读取
# @author           : OneYoung
# @create           : 2024/07/18
# @version          : v1.0
# @desc             :

import openpyxl
from xlrd import open_workbook


def read_from_txt(txt_file):
    """
    从txt文件读取数据
    :param txt_file: txt文件
    """
    with open(txt_file, 'r', encoding='utf-8') as f:
        content = f.read()
    return content


def read_from_excel(excel_name, sheet_name='Sheet1'):
    """
    从Excel中读取数据
    :param excel_name: Excel文件, 后缀为xls/xlsx
    :param sheet_name: 读取那个Sheet中的内容
    """
    data_list = {}
    # 获取文件后缀，不同后缀调用不同的方法解析
    suffix = excel_name.split('.')[-1]
    try:
        if suffix == "xlsx":
            wb = openpyxl.load_workbook(excel_name)
            sheet = wb[sheet_name]
            values = list(sheet.values)
            for value in values:
                data_list[value[0]] = value[1]
        elif suffix == "xls":
            file = open_workbook(excel_name)
            sheet = file.sheet_by_name(sheet_name)
            rows = sheet.nrows
            for i in range(rows):
                data_list[sheet.row_values(i)[0]] = sheet.row_values(i)[1]
        else:
            raise TypeError("不是有效的Excel文件.")
    except FileNotFoundError:
        raise FileNotFoundError(f"文件{excel_name}不存在.")
    return data_list
